<?php

namespace app\admin\controller;

use app\common\model\DistrictModel;

class District extends Common
{
    /**
     * 区划列表
     * @author 贺强
     * @time   2022/4/1 14:35
     */
    public function lists()
    {
        $keyword = $this->request->get('keyword', '');
        $where = [['level', '=', 1]];
        if (!empty($keyword)) {
            $where[] = ['name|code', 'like', "%$keyword%"];
        }
        // 分页参数
        $page = intval($this->request->get('page', 1));
        $pagesize = intval($this->request->get('pagesize', env('app.pagesize', 20)));
        $list = DistrictModel::getList($where, true, [$page, $pagesize], ['code' => 'asc']);
        foreach ($list as &$item) {
            format_datetime($item['ctime']);
            if ($item['mtime']) {
                format_datetime($item['mtime']);
            }
            $item['level_txt'] = get_district_level($item['level']);
            $item['status_txt'] = get_district_status($item['status']);
            if (!empty($item['children'])) {
                $item['has_children'] = 1;
                $children = json_decode($item['children'], true);
                $tip = [];
                if (!empty($children['city'])) {
                    $tip[] = "地级:{$children['city']}";
                }
                if (!empty($children['county'])) {
                    $tip[] = "县级:{$children['county']}";
                }
                if (!empty($children['village'])) {
                    $tip[] = "乡级:{$children['village']}";
                }
                $item['tip'] = implode('<br>', $tip);
                $item['children'] = $children;
            } else {
                $item['has_children'] = 0;
                $item['tip'] = '';
            }
        }
        if ($this->request->isAjax()) {
            return ajax('获取成功', 200, $list);
        }
        $count = DistrictModel::getCount($where);
        $pages = ceil($count / $pagesize);
        return view('list', compact('list', 'pages', 'keyword'));
    }

    /**
     * ajax 获取区划
     * @author 贺强
     * @time   2022/4/26 9:40
     */
    public function ajaxArea()
    {
        if (!$this->request->isAjax() || !$this->request->isPost()) {
            $this->error('非法操作');
        }
        $param = $this->request->post();
        $pcode = $param['code'] ?? '0';
        if ($pcode === '0') {
            $page = $param['page'] ?? 1;
            $pagesize = $param['pagesize'] ?? env('app.pagesize', 20);
            $where = [['pcode', '=', $pcode]];
            if (!empty($param['keyword'])) {
                $where[] = ['name|code', 'like', "%{$param['keyword']}%"];
            }
            $list = DistrictModel::getList($where, true, [$page, $pagesize], ['code' => 'asc']);
        } else {
            $list = DistrictModel::getList(['pcode' => $pcode]);
        }
        foreach ($list as &$item) {
            format_datetime($item['ctime']);
            if ($item['mtime']) {
                format_datetime($item['mtime']);
            }
            $item['level_txt'] = get_district_level($item['level']);
            $item['status_txt'] = get_district_status($item['status']);
            if (!empty($item['children'])) {
                $item['has_children'] = 1;
                $children = json_decode($item['children'], true);
                $tip = [];
                if (!empty($children['city'])) {
                    $tip[] = "地级:{$children['city']}";
                }
                if (!empty($children['county'])) {
                    $tip[] = "县级:{$children['county']}";
                }
                if (!empty($children['village'])) {
                    $tip[] = "乡级:{$children['village']}";
                }
                $item['tip'] = implode('<br>', $tip);
            } else {
                $item['has_children'] = 0;
                $item['tip'] = '';
            }
        }
        return ajax('获取成功', 200, $list);
    }

    /**
     * 区划列表
     * @author 贺强
     * @time   2022/4/1 14:35
     */
    public function lists1()
    {
        $keyword = $this->request->get('keyword', '');
        $where = [['level', '=', 1]];
        if (!empty($keyword)) {
            $where[] = ['name|code', 'like', "%$keyword%"];
        }
        // 分页参数
        $page = intval($this->request->get('page', 1));
        $pagesize = intval($this->request->get('pagesize', env('app.pagesize', 20)));
        $list = DistrictModel::getList($where, true, [$page, $pagesize], ['code' => 'asc']);
        foreach ($list as &$item) {
            format_datetime($item['ctime']);
            if ($item['mtime']) {
                format_datetime($item['mtime']);
            }
            $item['level_txt'] = get_district_level($item['level']);
            $item['status_txt'] = get_district_status($item['status']);
            $prefix = substr($item['code'], 0, 2);
            $count1 = DistrictModel::getCount([['code', 'like', "{$prefix}%"], ['pcode', '=', $item['code']]]);
            $count2 = DistrictModel::getCount([['code', 'like', "{$prefix}%"], ['level', '=', 3]]);
            $count3 = DistrictModel::getCount([['code', 'like', "{$prefix}%"], ['level', '=', 4]]);
            if ($count1 + $count2 > 0) {
                $item['tip'] = '地级:' . $count1 . '个<br>县级:' . $count2 . '个';
                if ($count3) {
                    $item['tip'] .= ('<br>乡级' . $count3 . '个');
                }
                $item['has_children'] = 1;
            } else {
                $item['tip'] = '';
                $item['has_children'] = 0;
            }
        }
        $count = DistrictModel::getCount($where);
        $pages = ceil($count / $pagesize);
        return view('list1', compact('list', 'pages', 'keyword'));
    }

    /**
     * ajax 获取区划
     * @author 贺强
     * @time   2022/4/26 9:40
     */
    public function ajaxArea1()
    {
        if (!$this->request->isAjax() || !$this->request->isPost()) {
            $this->error('非法操作');
        }
        $param = $this->request->post();
        $pcode = $param['code'] ?? '0';
        if ($pcode === '0') {
            $page = $param['page'] ?? 1;
            $pagesize = $param['pagesize'] ?? env('app.pagesize', 20);
            $where = [['pcode', '=', $pcode]];
            if (!empty($param['keyword'])) {
                $where[] = ['name|code', 'like', "%{$param['keyword']}%"];
            }
            $list = DistrictModel::getList($where, true, [$page, $pagesize], ['code' => 'asc']);
        } else {
            $list = DistrictModel::getList(['pcode' => $pcode]);
        }
        foreach ($list as &$item) {
            format_datetime($item['ctime']);
            if ($item['mtime']) {
                format_datetime($item['mtime']);
            }
            $item['level_txt'] = get_district_level($item['level']);
            $item['status_txt'] = get_district_status($item['status']);
            $level = intval($item['level']);
            if ($level === 3) {
                $prefix = substr($item['code'], 0, 6);
                $count = DistrictModel::getCount([['code', 'like', "{$prefix}%"], ['level', '=', 4]]);
                if ($count) {
                    $item['tip'] = '乡级:' . $count . '个';
                    $item['has_children'] = 1;
                } else {
                    $item['tip'] = '';
                    $item['has_children'] = 0;
                }
            } elseif ($level === 2) {
                $prefix = substr($item['code'], 0, 4);
                $count = DistrictModel::getCount([['code', 'like', "{$prefix}%"], ['level', '=', 3]]);
                $count2 = DistrictModel::getCount([['code', 'like', "{$prefix}%"], ['level', '=', 4]]);
                if ($count) {
                    $item['tip'] = '县级:' . $count . '个';
                    if ($count2) {
                        $item['tip'] .= ('<br>乡级' . $count2 . '个');
                    }
                    $item['has_children'] = 1;
                } else {
                    $item['tip'] = '';
                    $item['has_children'] = 0;
                }
            } elseif ($level === 1) {
                $prefix = substr($item['code'], 0, 2);
                $count1 = DistrictModel::getCount([['code', 'like', "{$prefix}%"], ['level', '=', 2]]);
                $count2 = DistrictModel::getCount([['code', 'like', "{$prefix}%"], ['level', '=', 3]]);
                $count3 = DistrictModel::getCount([['code', 'like', "{$prefix}%"], ['level', '=', 4]]);
                if ($count1) {
                    $item['tip'] = '地级:' . $count1 . '个';
                    if ($count2) {
                        $item['tip'] .= '<br>县级' . $count2 . '个';
                        if ($count3) {
                            $item['tip'] .= '<br>乡级' . $count3 . '个';
                        }
                    }
                    $item['has_children'] = 1;
                } else {
                    $item['tip'] = '';
                    $item['has_children'] = 0;
                }
            } else {
                $item['tip'] = '';
                $item['has_children'] = 0;
            }
        }
        return ajax('获取成功', 200, $list);
    }

    /**
     * 添加区划
     * @author 贺强
     * @time   2022/5/24 13:44
     */
    public function add()
    {
        if ($this->request->isPost()) {
            if (!empty($this->admin['code'])) {
                return $this->admin;
            }
            $data = $this->request->post();
            if (empty($data['code']) || empty($data['name']) || empty($data['level'])) {
                return ajax('参数缺失', 101);
            }
            $level = intval($data['level']);
            if ($level > 1 && empty($data['pcode'])) {
                return ajax('父级编码不能为空', 103);
            }
            $has = DistrictModel::getCount(['code' => $data['code']]);
            if ($has) {
                return ajax('区划编码已存在', 102);
            }
            $data['mtime'] = 0;
            $res = DistrictModel::add($data);
            if (!$res) {
                return ajax('添加失败', 400);
            }
            if ($level > 1) {
                queue('app\\common\\job\\EsJob@refresh_add_district', $data['code']);
            }
            return ajax('添加成功');
        }
        $code = $this->request->get('code', '0');
        if (empty($code)) {
            $model = ['code' => '0', 'level' => 0, 'name' => '全国'];
        } else {
            $model = DistrictModel::getModel(['code' => $code], ['level', 'code', 'name']);
        }
        $level = $model['level'] + 1;
        return view('', compact('level', 'model'));
    }

    /**
     * 修改区划
     * @author 贺强
     * @time   2022/5/24 13:45
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            if (!empty($this->admin['code'])) {
                return $this->admin;
            }
            $data = $this->request->post();
            if (empty($data['code'])) {
                return ['status' => 2, 'info' => '参数失败'];
            }
            if (empty($data['pcode'])) {
                $data['pcode'] = '0';
            }
            if (!empty($data['status'])) {
                switch ($data['status']) {
                    case 1:
                        $this->ena_par_item($data['code']);
                        break;
                    case 2:
                        $this->dis_sub_item($data['code']);
                        break;
                }
            }
            $res = DistrictModel::modify($data, ['code' => $data['code']]);
            if ($res === false) {
                return ajax('修改失败', 400);
            }
            return ajax('修改成功');
        }
        $code = $this->request->get('code', '');
        if (empty($code) || !is_numeric($code)) {
            $this->error('非法参数');
        }
        $district = DistrictModel::getModel(['code' => $code], true, '', 0);
        $pcodes = [];
        if (!empty($district['pcode'])) {
            $pcode = DistrictModel::getFieldValue('pcode', ['code' => $district['pcode']]);
            $pcodes = DistrictModel::getList(['pcode' => $pcode], ['code', 'name']);
        }
        return view('', compact('district', 'pcodes'));
    }

    /**
     * 删除区划
     * @author 贺强
     * @time   2022/5/24 13:45
     */
    public function del()
    {
        if (!$this->request->isPost()) {
            return ajax('非法操作', 101);
        }
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $code = $this->request->post('code', '');
        if (empty($code)) {
            return ajax('非法参数', 102);
        }
        $district = DistrictModel::getModel(['code' => $code]);
        if (empty($district)) {
            return ajax('区划不存在', 103);
        }
        queue('app\\common\\job\\EsJob@refresh_del_district', $district);
        return ajax('删除成功');
    }

    /**
     * 删除区划
     * @author 贺强
     * @time   2022/5/24 13:45
     */
    public function del1()
    {
        if (!$this->request->isPost()) {
            return ajax('非法操作', 101);
        }
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $code = $this->request->post('code', '');
        if (empty($code)) {
            return ajax('非法参数', 102);
        }
        $this->del_sub_item($code);
        return ajax('删除成功');
    }

    /**
     * 批量操作
     * @author 贺强
     * @time   2022/8/24 9:22
     */
    public function operate()
    {
        if (!$this->request->isPost()) {
            $this->error('非法操作');
        }
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $type = $this->request->post('type', '');
        $ids = $this->request->post('ids', []);
        if (empty($type) || empty($ids)) {
            return ajax('非法参数', 101);
        }
        if ($type === 'enableAll' || $type === 'enable') {
            foreach ($ids as $code) {
                $this->ena_par_item($code);
                // $this->ena_sub_item($code);
            }
            return ajax('修改成功');
        } elseif ($type === 'disableAll' || $type === 'disable') {
            foreach ($ids as $code) {
                $this->dis_sub_item($code);
            }
            return ajax('修改成功');
        } elseif ($type === 'del' || $type === 'delAll') {
            foreach ($ids as $code) {
                $this->del_sub_item($code);
            }
            return ajax('删除成功');
        }
        return ajax('无操作', 201);
    }

    /**
     * 重刷
     * @author 贺强
     * @time   2023/4/18 9:47
     */
    public function refresh()
    {
        if (!$this->request->isAjax() || !$this->request->isPost()) {
            $this->error('非法操作');
        }
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $code = $this->request->post('code', '');
        queue('app\\common\\job\\EsJob@refresh_district', $code);
        return ajax('重刷成功');
    }

    /**
     * 递归删除子项
     * @param $code string 区划编码
     * @author 贺强
     * @time   2022/5/25 9:07
     */
    private function del_sub_item($code)
    {
        $list = DistrictModel::getField('code', ['pcode' => $code]);
        if ($list) {
            DistrictModel::delByWhere(['pcode' => $code]);
            foreach ($list as $item) {
                $this->del_sub_item($item['code']);
            }
        }
        DistrictModel::delByWhere(['code' => $code]);
    }

    /**
     * 递归禁用子项
     * @param $code string 区划编码
     * @author 贺强
     * @time   2022/8/25 9:02
     */
    private function dis_sub_item($code)
    {
        $list = DistrictModel::getField('code', ['pcode' => $code]);
        if ($list) {
            DistrictModel::modify(['status' => 2], ['pcode' => $code]);
            foreach ($list as $item) {
                $this->dis_sub_item($item['code']);
            }
        }
        DistrictModel::modify(['status' => 2], ['code' => $code]);
    }

    /**
     * 递归启用父级
     * @param $code string 区划编码
     * @author 贺强
     * @time   2022/8/25 9:11
     */
    private function ena_par_item($code)
    {
        DistrictModel::modify(['status' => 1], ['code' => $code]);
        $pcode = DistrictModel::getFieldValue('pcode', ['code' => $code]);
        if ($pcode) {
            DistrictModel::modify(['status' => 1], ['code' => $pcode]);
            $this->ena_par_item($pcode);
        }
    }

    /**
     * 递归启用子项
     * @param $code string 区划编码
     * @author 贺强
     * @time   2022/8/25 9:39
     */
    // private function ena_sub_item($code)
    // {
    //     $list = DistrictModel::getField('code', ['pcode' => $code]);
    //     if ($list) {
    //         DistrictModel::modify(['status' => 1], ['pcode' => $code]);
    //         foreach ($list as $item) {
    //             $this->ena_sub_item($item['code']);
    //         }
    //     }
    //     DistrictModel::modify(['status' => 1], ['code' => $code]);
    // }
}
